package com.woniu.consumer;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.woniu.entity.KillOrder;
import com.woniu.entity.RabbitmqConst;
import com.woniu.mapper.OrderMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 消费者重复消费问题
 * 出现原因：消费者消费结束，答应通过网络发出去了，但是因为网络波动等原因，队列没有收到
 *         导致消费者重复消费消息
 * 怎么解决
 *      1：在生产者发消息时，获取该消息的唯一信息，存入redis中
 *      2：在消费消息时，先去删除redis的数据，删除成功才能消费，删除不成功不能消费
 *
 */
@Component
public class AddKillOrderConsumer {

    @Resource
    private OrderMapper orderMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @RabbitListener(queues = RabbitmqConst.ADDKILLBOOK_QUEUE)
    public void receive(String msg, Channel channel , Message message){
        try {
            KillOrder killOrder = JSON.parseObject(msg, KillOrder.class);
            //解决重复消费的问题，先删除消息，删成功再执行操作
            if (redisTemplate.delete(killOrder.getKillOrderNum())){
                orderMapper.addKillOrder(killOrder);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);

        }
    }
}
